'use strict';
const { verifyJwt, loginResponse } = require('auth-token')
exports.main = async (event, context) => {
	// 需登录才能访问
	const payload = verifyJwt(event.token)
	if (!payload) {
	  return loginResponse()
	}
	const currentUid = payload._id
	
	// 数据库连接
	const dbJQL = uniCloud.databaseForJQL({event, context})
	const groupCollection = dbJQL.collection('ume-group')
	
	const blockMark = event.params.block;
	// 业务逻辑
	switch (event.action) {
	  case 'userRetrieve':
		console.log('blockMark:', blockMark);
	    // 用户请求自己的分组信息
	    const ledger = await groupCollection.where(`state==true && block_mark=='${blockMark}' && (user_id==''||user_id=='${currentUid}')`).get()
	    // console.log("ledge:", ledger.data)
	    return {
	      groups: ledger.data,
	      message: '获取分组成功!'
	    }
	    break;
	  case 'userRetrieveTree':
	    // 用户查询自己的分类信息，树形返回
	    const treeRes = await groupCollection.where(`state==true && (user_id==''||user_id=='${currentUid}')`).get({getTree: true})
	    // console.log("treeRes:", treeRes.data)
	    return {
	      ledger: treeRes.data,
	      message: '获取分类成功!'
	    }
	    break;
	    
	  case 'userUpdate':
	    const ledgerId = event._id
	    const group_name = event.group_name
	    const ledgerRowRes = await groupCollection.doc(ledgerId).get({getOne: true});
	    // console.log('ledgerRowRes:', ledgerRowRes)
	    const ledgerRow = ledgerRowRes.data
	    if (!ledgerRow.user_id) {
	      return {
	        _id: '',
	        message: '系统内置分类，请不要进行修改!'
	      }
	    } else {
	      await groupCollection.doc(ledgerId).update({group_name: group_name})
	      return {
	        _id: ledgerId,
	        message: '修改成功!'
	      }
	    }
	    break;
	  case 'userDelete':
	    const delId = event._id
	    const delRowRes = await groupCollection.where(`_id=='${delId}'`).get({getOne: true});
	    const delRow = delRowRes.data
	    // console.log('delRowRes:',delRowRes )
	    if (!delRow.user_id) {
	      return {
	        _id: '',
	        message: '系统内置分类，不能删除!'
	      }
	    }
	    // const childRes = await groupCollection.where(`parent_id=='${delRow._id}'`).get({getOne: true})
	    // // 是否有子集
	    // if (childRes.data) {
	    //   return {
	    //     _id: '',
	    //     message: '该分类有子集，不能删除!'
	    //   }
	    // }
			
			// 根据blockMark查询是否有数据，有的话不支持删除
			// console.log('操作删除Mark:', blockMark)
			let relateCollection = null;
			if (blockMark == 'PWD') {
				let relateCollection = dbJQL.collection('ume-notebook')
				let childRes = await relateCollection.where(`user_id=='${currentUid}' && group_id=='${delId}'`).get({getOne: true})
				if (childRes.data) {
					return {_id: '',message: '包含相关数据，不能删除!'}
				}
			} else {
				return {
					_id: '',
					message: '该类型暂不支持删除!'
				}
			}
			// 进入删除
			groupCollection.doc(delId).remove() 
			return {
			  _id: delId,
			  message: '删除成功!'
			}
	    break;
	  case 'userCreate':
	    const createData = event.group_data
	    let newLedger;
	    if (createData.parent_id) {
	      // 创建子类
	      newLedger = {
	        group_name: createData.group_name,
	        parent_id: createData.parent_id,
					block_mark: blockMark,
	        user_id: currentUid
	      }
	    } else  {
	      // 创建父类
	      newLedger = {
	        group_name: createData.group_name,
	        parent_id: '',
	        user_id: currentUid,
					block_mark: blockMark
	      }
	    }
	    const addRes = await groupCollection.add(newLedger)
	    return {
	      _id: addRes.id,
	      message: '创建分组成功!'
	    }
	  default:
	    break
	}
	return {
	  message: '没有进行任何操作!'
	}
};
